package com.paic.mhis.hcpms.assessment.web;

import java.awt.Color;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import com.paic.mhis.core.exception.FwaBusinessException;
import com.paic.mhis.hcpms.assessment.biz.service.ExportWordService;
import com.paic.mhis.hcpms.assessment.biz.service.ScoreTableService;
import com.paic.mhis.hcpms.assessment.biz.service.WebSpiderService;
import com.paic.mhis.hcpms.assessment.common.AssessmentConstants;
import com.paic.mhis.hcpms.assessment.dto.CodeAndScore;
import com.paic.mhis.hcpms.assessment.dto.CodeNameAndScore;
import com.paic.mhis.hcpms.assessment.dto.ScoreTableDTO;
import com.paic.mhis.hcpms.assessment.dto.SecondLevelIndicatorDto;
import com.paic.mhis.hcpms.assessment.util.AssessmentUtils;
import com.paic.mhis.hcpms.assessment.util.ScaleSpriderWebPlotFactory;
import com.paic.mhis.hcpms.evaluation.intergration.dto.FwaOrgDTO;
import com.paic.mhis.hcpms.quota.exportword.utils.GeneralMethods;
import com.paic.pafa.app.integration.sa.PafaSAOException;
import com.paic.pafa.app.lwc.core.util.CollectionUtils;
import com.paic.pafa.appclient.annotation.BizServicesProxy;

/**
 * Description: 导出word的controller
 * 
 * @author: EX-TIANZINONG001
 * @version:
 */
@Controller
@RequestMapping("/assessment/")
public class ExportWordController {
	private static final Log LOG = LogFactory
			.getLog(ExportWordController.class);

	private static final String UPRESULT = " 上 升  ";

	private static final String DOWNRESULT = " 下 降 ";

	private static final String EQUALITY = " 相 等  ";

	private static final String CLASS_UPRESULT = "高于";

	private static final String CLASS_DOWNRESULT = "低于";

	private static final String CLASS_EQUALITYRESULT = "等于";

	private static final String CITY = "全市排名   ";

	private static final String GRADE = "同级别医院排名 ";

	private static final String CLASSES = "同类别医院排名";

	// table
	public static final int MENU_GRADE_FIRST = 1;

	public static final int MENU_GRADE_SECOND = 2;

	public static final int MENU_GRADE_THREE = 3;

	private static final String TAB_SUFFIX = "_tab.rtf";

	private static final String FIRST_PART = "FIRSTPART";

	private static final String RE_IMG = "IMG";

	private static final String RE_TABLE = "TABLE";

	private static final String FIFTHPART = "evaluation";

	private static final String TEMPLATEANDSUFFIX = "template.rtf";

	private static final String STRTEMPLATESUFFIX = "strTemplate.rtf";

	private static final String WORD_SUFFIX = "_word.rtf";

	private static final String ROOTPATH = "/wls/wldomains/DEV4CIDomain/servers/Dev4CiWebServer/tmp/_WL_user/mhis-fwa/p5hydp/war/";

	private static final int WIDTH = 700;

	private static final int HEIGHT = 300;

	@BizServicesProxy(beanName = "exportWordService")
	private ExportWordService exportWordService;

	@BizServicesProxy(beanName = "WebSpiderService")
	private WebSpiderService webSpiderService;

	@BizServicesProxy(beanName = "scoreTableService")
	private ScoreTableService scoreTableService;

	@Value("${rtfReportTemplatePath}")
	private String rtfReportTemplatePath;

	/**
	 * Description: 在服务器上写好word的方法
	 * 
	 * @param request
	 * @param response
	 * @return Map 返回到前台判断文档是否书写成功的结果
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 */
	@RequestMapping("writeFile.do")
	@ResponseBody
	public Map<String, Object> writeFileReq(HttpServletRequest request) {
		String providerCode = request.getParameter("providerCode");
		String kpiTime = request.getParameter("kpiTime");
		// request.getSession().getServletContext().getRealPath("/")
		String assessPath = rtfReportTemplatePath + "assessment/";
		// String assessPath = request.getSession().getServletContext()
		// .getRealPath("/")
		// + "RTFReportTemplateDir/assessment/";
		LOG.info("写文档·············································"
				+ assessPath);
		Map<String, Object> mapResult = new HashMap<String, Object>();
		// 存放生成word的路径
		String outputPath = assessPath + "orgDetail/";
		String temPath = outputPath + TEMPLATEANDSUFFIX;
		String pngPath = assessPath + "img/";
		String fileName = providerCode + "-" + kpiTime;
		Map<String, Object> map = null;
		String msg = "生成word成功!";
		boolean flag = true;
		if (StringUtils.isEmpty(providerCode) || StringUtils.isEmpty(kpiTime)) {
			LOG.info(msg);
			flag = false;
			msg = "导出失败!";
			getResultMap(mapResult, msg, flag);
		}
		Map<String, Object> dateMapParameter = new HashMap<String, Object>();
		dateMapParameter.put("coding", providerCode);
		dateMapParameter.put("nowDate", kpiTime);
		dateMapParameter.put("lastDate", getLastMonth(kpiTime));
		float totalScore = exportWordService.getTotal(dateMapParameter);
		if (totalScore > 0 && flag) {
			try {

				getResultMap(mapResult, msg, flag);
				map = exportWordService.getHospitalInfo(providerCode);
				mapValueIsNotNUll(map);
				dateMapParameter.put("grade", map.get("HOSLEVEL"));
				dateMapParameter.put("regioncode", map.get("REGIONCODE"));
				// map.put("MONTH", new
				// SimpleDateFormat("yyyy-MM").parse(kpiTime)
				// .getMonth() + 1);
				map.put("NEWDATE", kpiTime);
				map.put("SCORE", AssessmentUtils
						.decimalToString(new BigDecimal(totalScore)));
				String content = getContent(temPath);
				String firstPart = getFirstPartString(dateMapParameter);
				map.put(FIRST_PART, firstPart);
				Map<String, Object> repScoreMap = new HashMap<String, Object>();
				String structureNo = exportWordService
						.getStructureNo(dateMapParameter);
				dateMapParameter.put("structureNO", structureNo);
				List<CodeAndScore> codeAndScoreList = exportWordService
						.getindicatorCodeAndScore(dateMapParameter);
				String[] lineArr = null;
				String[] faceArr = null;
				for (int i = 0; i < codeAndScoreList.size(); i++) {
					lineArr = getStringForScore(
							Double.parseDouble(AssessmentUtils
									.decimalToString(codeAndScoreList.get(i)
											.getCurrentScore()))
									- Double.parseDouble(AssessmentUtils
											.decimalToString(codeAndScoreList
													.get(i).getLastScore())),
							pngPath);
					faceArr = getStringForPercent(
							Double.parseDouble(AssessmentUtils
									.decimalToString(codeAndScoreList.get(i)
											.getCurrentScore())),
							Double.parseDouble(AssessmentUtils
									.decimalToString(codeAndScoreList.get(i)
											.getAvgScore())), pngPath);
					repScoreMap.put(codeAndScoreList.get(i).getIndicatorCode()
							+ "_a", Double.parseDouble(AssessmentUtils
							.decimalToString(codeAndScoreList.get(i)
									.getCurrentScore())));
					repScoreMap.put(codeAndScoreList.get(i).getIndicatorCode()
							+ "_b", lineArr[0]);
					repScoreMap.put(codeAndScoreList.get(i).getIndicatorCode()
							+ "_c", faceArr[0]);
					content = content.replace(codeAndScoreList.get(i)
							.getIndicatorCode() + "_picb", lineArr[1]);
					content = content.replace(codeAndScoreList.get(i)
							.getIndicatorCode() + "_picc", faceArr[1]);
				}
				content = replaceContentForCode(content, map);
				content = replaceContentForCode(content, repScoreMap);
				List<ArrayList<SecondLevelIndicatorDto>> indicatorList = webSpiderService
						.findLevel2IndictorList(providerCode, kpiTime,
								structureNo, (String) map.get("REGIONCODE"),
								(String) map.get("HOSLEVEL"));
				content = content.replace(
						RE_IMG,
						getImgStringForPath(pngPath, providerCode, kpiTime,
								indicatorList));
				// 生成和替换表格 传医院等级和统筹区域编码
				List<ScoreTableDTO> tabList = scoreTableService
						.createReportsTable(dateMapParameter);
				createTable(tabList, outputPath + fileName + TAB_SUFFIX);
				String tabStr = getTableCode(outputPath + fileName + TAB_SUFFIX);
				content = content.replace(RE_TABLE, tabStr);

				/**
				 * 第四部分
				 */
				content = getForthPartStr(content, providerCode, kpiTime
						+ "-01", getLastDayOfMonth(kpiTime));
				content = getFifthPartStr(providerCode, kpiTime,
						(String) map.get("REGIONCODE"), structureNo,
						(String) map.get("HOSLEVEL"), content, outputPath);
				exportWord(content, outputPath, fileName + WORD_SUFFIX);
			} catch (Exception e) {
				LOG.error(e, e);
				flag = false;
				msg = "导出失败!";
				getResultMap(mapResult, msg, flag);
			}
		} else {
			flag = false;
			msg = "导出失败，总分尚未生成!";
			getResultMap(mapResult, msg, flag);
		}
		return mapResult;
	}

	/**
	 * 
	 * Description:
	 * 
	 * @param mapResult
	 * @param msg
	 * @param flag
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-13 mhis_hcpms EX-TIANZINONG001 创建
	 */
	public void getResultMap(Map<String, Object> mapResult, String msg,
			boolean flag) {
		mapResult.put("msg", msg);
		mapResult.put("flag", flag);
	}

	/**
	 * Description: 获得JFreeChar生成图片的String
	 * 
	 * @param pngPath
	 *            图片路径
	 * @param providerCode
	 *            医院编码
	 * @param kpiTime
	 *            查询时间
	 * @param indicatorList
	 *            集合
	 * @return String ------------------------------------------------------
	 *         2015-3-13 mhis_hcpms EX-TIANZINONG001 创建
	 */
	public String getImgStringForPath(String pngPath, String providerCode,
			String kpiTime,
			List<ArrayList<SecondLevelIndicatorDto>> indicatorList) {
		int[] size = { WIDTH, HEIGHT };
		String picPath = "";
		try {
			picPath = findPngFilePath(pngPath, providerCode, kpiTime,
					indicatorList, size);
		} catch (IOException e) {
			LOG.error(e, e);
		}
		String picStr = getImgRtfCode2(picPath);
		return picStr;
	}

	/**
	 * 
	 * Description: 第四部分的内容 // 先查询数据// 读取子模板 得到字符串// 替换模板
	 * 
	 * @param providerCode
	 * @param kpiTime
	 * @param content
	 * @param outputPath
	 * @return
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 * @throws PafaSAOException
	 */
	public String getForthPartStr(String content, String medicalOrgCode,
			String startDate, String endDate) {
		String str = content;
		try {
			Map<String, Object> map = exportWordService.getForthPartStr(
					medicalOrgCode, startDate, endDate);
			List<FwaOrgDTO> list = (List<FwaOrgDTO>) map.get("list");

			if (!CollectionUtils.isEmpty(list)) {
				for (int i = 0; i < list.size(); i++) {
					if (StringUtils.equals(list.get(i).getName(), "可疑")) {
						str = str.replace("fwa_name1", list.get(i).getName());
						str = str.replace("fwa_num1", list.get(i).getNum());
						str = str.replace("fwa_money1", list.get(i).getMoney());
						str = str.replace("fwa_result1", map
								.get("suspiciousPersonNum") == null ? "" : map
								.get("suspiciousPersonNum").toString());
					}
					if (StringUtils.equals(list.get(i).getName(), "高度可疑")) {
						str = str.replace("fwa_name2", list.get(i).getName());
						str = str.replace("fwa_num2", list.get(i).getNum());
						str = str.replace("fwa_money2", list.get(i).getMoney());
						str = str.replace("fwa_result2", map
								.get("highlySuspiciousPersonNum") == null ? ""
								: map.get("highlySuspiciousPersonNum")
										.toString());
					}
					if (StringUtils.equals(list.get(i).getName(), "违规")) {
						str = str.replace("fwa_name3", list.get(i).getName());
						str = str.replace("fwa_num3", list.get(i).getNum());
						str = str.replace("fwa_money3", list.get(i).getMoney());
						str = str.replace("fwa_result3", map
								.get("outOfLinePersonNum") == null ? "" : map
								.get("outOfLinePersonNum").toString());
					}

				}
			}
		} catch (Exception e) {
			LOG.error(e, e);
			LOG.info("FWA审核接口调用异常");
			return replaceStringTo(str);
		}

		return str;
	}

	public String replaceStringTo(String str) {
		for (int i = 0; i < 3; i++) {
			str = str.replace("fwa_name" + (i + 1), "");
			str = str.replace("fwa_num" + (i + 1), "");
			str = str.replace("fwa_result" + (i + 1), "");
			str = str.replace("fwa_money" + (i + 1), "");
		}
		return str;
	}

	/**
	 * 
	 * Description: 第五部分的内容 // 先查询数据// 读取子模板 得到字符串// 替换模板
	 * 
	 * @param providerCode
	 * @param kpiTime
	 * @param content
	 * @param outputPath
	 * @return
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 */
	public String getFifthPartStr(String providerCode, String kpiTime,
			String regionCode, String structureNo, String grade,
			String content, String outputPath) {
		String str = content;
		List<CodeNameAndScore> scoreList = exportWordService
				.getCodeNameAndScore(providerCode, kpiTime, regionCode,
						structureNo, grade);
		String fifthPartcontent = getContent(outputPath + STRTEMPLATESUFFIX);
		String fifthPartStr = getFifthPartString(scoreList, fifthPartcontent);
		str = str.replace(FIFTHPART, fifthPartStr);
		return str;
	}

	/**
	 * Description: 得到第四部分子模板的字符串
	 * 
	 * @param scoreList
	 * @param forthPartcontent
	 * @return ------------------------------------------------------ 2015-3-10
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 */
	private String getFifthPartString(List<CodeNameAndScore> scoreList,
			String forthPartcontent) {
		StringBuilder str = new StringBuilder();
		String ss = "";
		for (int i = 0; i < scoreList.size(); i++) {
			ss = forthPartcontent.replace("codeName", getStrRtfCode(scoreList
					.get(i).getInCodeName()));
			ss = ss.replace(
					"currScore",
					AssessmentUtils.decimalToString(scoreList.get(i)
							.getCurrScore()) + "");

			ss = ss.replace(
					"avgScore",
					AssessmentUtils.decimalToString(scoreList.get(i)
							.getAvgScore()) + "");
			str.append(ss);
		}
		return str.toString();
	}

	/**
	 * Description: 导出文档
	 * 
	 * @param request
	 * @param response
	 * 
	 *            2015-3-10 mhis_hcpms EX-TIANZINONG001 创建
	 */
	@RequestMapping("exportFile.do")
	@ResponseBody
	public void exportFileRes(HttpServletRequest request,
			HttpServletResponse response) {
		// 导出word
		String hospitalName = request.getParameter("hospitalName");
		String providerCode = request.getParameter("providerCode");
		String kpiTime = request.getParameter("kpiTime");
		String assessPath = rtfReportTemplatePath + "assessment/";
		// String assessPath = request.getSession().getServletContext()
		// .getRealPath("/")
		// + "RTFReportTemplateDir/assessment/";
		String outputPath = assessPath + "orgDetail/";
		String fileName = providerCode + "-" + kpiTime;

		exportWordByResAndFile(response, outputPath + fileName + WORD_SUFFIX,
				kpiTime, hospitalName);
	}

	/**
	 * Description:将文档读入程序
	 * 
	 * @param response
	 * @param s
	 * 
	 *            2015-3-10 mhis_hcpms EX-TIANZINONG001 创建
	 */
	private void exportWordByResAndFile(HttpServletResponse response, String s,
			String kpiTime, String hospitalName) {
		FileInputStream fis = null;
		OutputStream fos = null;
		int len = 1024;
		try {
			fis = new FileInputStream(new File(s));
			initResponse(response, hospitalName + "综合评价报告" + "(" + kpiTime
					+ ")");
			byte[] byteArr = new byte[len];
			fos = response.getOutputStream();
			while (fis.read(byteArr) != -1) {
				fos.write(byteArr);
			}
		} catch (FileNotFoundException e) {
			LOG.error(e, e);
		} catch (IOException e) {
			LOG.error(e, e);
		} finally {
			try {
				if (null != fis) {
					fis.close();
				}
				if (null != fos) {
					fos.close();
				}
			} catch (Exception e) {
				LOG.error(e, e);
			}
		}
	}

	/**
	 * 
	 * Description: 返回导出的word
	 * 
	 * @param response
	 * @param name
	 *            文件名
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-13 mhis_hcpms EX-TIANZINONG001 创建
	 */
	private void initResponse(HttpServletResponse response, String name) {
		try {
			response.addHeader("Pragma", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
			response.reset();
			response.setContentType("APPLICATION/OCTET-STREAM");
			String fileName = new String((name).getBytes("utf-8"), "ISO8859-1")
					+ ".rtf";
			response.setHeader("content-disposition", "attachment;fileName=\""
					+ fileName + "\"");
		} catch (UnsupportedEncodingException e) {
			LOG.error(e, e);
			LOG.error("导出word时发生异常,异常原因:" + e.getMessage());
		}
	}

	/**
	 * 
	 * Description: 如果map中值为null 给一个""
	 * 
	 * @param map
	 * 
	 *            Modification History: Date Version Author Description
	 *            ----------
	 *            --------------------------------------------------------
	 *            2015-3-13 mhis_hcpms EX-TIANZINONG001 创建
	 */
	private void mapValueIsNotNUll(Map<String, Object> map) {
		if (map == null) {
			return;
		}
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			if (null == entry.getValue()) {
				map.put(entry.getKey(), "");
			}
			// else if (StringUtils.equals(entry.getKey(), "HOSLEVEL")) {
			// if (StringUtils.equals((String) entry.getValue(), "2")) {
			// entry.setValue("三级");
			// } else if (StringUtils.equals((String) entry.getValue(), "3")) {
			// entry.setValue("二级");
			// } else if (StringUtils.equals((String) entry.getValue(), "4")) {
			// entry.setValue("一级");
			// }
			// }
		}
	}

	/**
	 * 获取当前视角的下个月份 Description:
	 * 
	 * @param kpiTime
	 * @return ------------------------------------------------------ 2015-3-3
	 *         mhis_hcpms EX-YUFEI002 创建
	 */
	public String getNextMonth(String kpiTime) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		try {
			Date date = format.parse(kpiTime);
			int year = date.getYear() + 1900;
			int month = date.getMonth();

			Calendar calendar = Calendar.getInstance();
			calendar.set(year, month, 13);
			calendar.add(Calendar.MONTH, 1);

			return format.format(calendar.getTime());
		} catch (ParseException e) {
			LOG.error(e, e);
		}

		return "";
	}

	/**
	 * 获取当前视角的上个月份 Description:
	 * 
	 * @param kpiTime
	 * @return ------------------------------------------------------ 2015-3-3
	 *         mhis_hcpms EX-YUFEI002 创建
	 */
	public String getLastMonth(String kpiTime) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		try {
			Date date = format.parse(kpiTime);
			int year = date.getYear() + 1900;
			int month = date.getMonth();

			Calendar calendar = Calendar.getInstance();
			calendar.set(year, month, 13);
			calendar.add(Calendar.MONTH, -1);

			return format.format(calendar.getTime());
		} catch (ParseException e) {
			LOG.error(e, e);
		}

		return "";
	}

	/**
	 * Description: 获取本月和上月相比得分的结果
	 * 
	 * @param result
	 *            结果
	 * @param pngPath
	 *            图片路径
	 * @return String
	 * 
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 */
	public String[] getStringForScore(double result, String pngPath) {
		String resultStr = "";
		String imgStr = "";
		String upImg = "up.png";
		String downImg = "down.png";
		// String sameImg = "same.png";
		String[] arr = new String[2];
		if (result > 0) {
			resultStr = UPRESULT + String.format("%.1f", Math.abs(result))
					+ " 分";
			imgStr = getImgRtfCode2(pngPath + upImg);
		} else if (result < 0) {
			resultStr = DOWNRESULT + String.format("%.1f", Math.abs(result))
					+ " 分";
			imgStr = getImgRtfCode2(pngPath + downImg);
		} else {
			resultStr = EQUALITY;
			// imgStr = getImgRtfCode2(pngPath + sameImg);
		}
		arr[0] = resultStr;
		arr[1] = imgStr;
		return arr;
	}

	/**
	 * 
	 * Description: 获取同等级机构的百分比
	 * 
	 * @param curr
	 *            当前分数
	 * @param avg
	 *            同等级机构平均分数
	 * @param imgPath
	 *            图片路径
	 * @return String
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-12
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 */
	public String[] getStringForPercent(double curr, double avg, String imgPath) {
		String resultStr = "";
		String imgStr = "";
		String subStr = "";
		String smileImg = "smile.png";
		String sadImg = "sad.png";
		// String sameImg = "same.png";
		int len = 2;
		double hundred = 100.00f;
		String[] arr = new String[len];
		double result = curr - avg;
		if (new Float(avg).equals(new Float(0f))) {
			resultStr = CLASS_UPRESULT + "平均分(" + avg + ")" + hundred + "%";
			imgStr = getImgRtfCode2(imgPath + smileImg);
		} else {
			subStr = String.format("%.1f", Math.abs(result / avg) * hundred)
					+ "%";
			if (result > 0) {
				resultStr = CLASS_UPRESULT + "平均分(" + avg + ")" + subStr;
				imgStr = getImgRtfCode2(imgPath + smileImg);
			} else if (result < 0) {
				resultStr = CLASS_DOWNRESULT + "平均分(" + avg + ")" + subStr;
				imgStr = getImgRtfCode2(imgPath + sadImg);
			} else {
				resultStr = CLASS_EQUALITYRESULT + "平均分(" + avg + ")";
				// imgStr = getImgRtfCode2(imgPath + sameImg);
			}
		}
		arr[0] = resultStr;
		arr[1] = imgStr;
		return arr;
	}

	/**
	 * Description:查询全市，同等级，同类别的排名结果
	 * 
	 * @param mapParamter
	 *            coding nowDate
	 * @return String ------------------------------------------------------
	 *         2015-3-11 mhis_hcpms EX-TIANZINONG001 创建
	 */
	public String getFirstPartString(Map<String, Object> mapParamter) {

		float cityCount = exportWordService.getCityCount(mapParamter);
		float cityRowNum = exportWordService.getCityRowNum(mapParamter);

		float gradeCount = exportWordService.getGradeCount(mapParamter);
		float gradeRowNum = exportWordService.getGradeRowNum(mapParamter);

		float classesCount = exportWordService.getClassesCount(mapParamter);
		float classesRowNum = exportWordService.getClassesRowNum(mapParamter);
		String result = "";
		int num = 1;
		if ((cityRowNum / cityCount) > 0.8 && ((int) cityRowNum != num)
				&& (int) cityCount != num) {
			result += CITY + (int) cityRowNum + "/" + (int) cityCount + "；"
					+ "\n";
		}
		if ((gradeRowNum / gradeCount) > 0.8 && (int) gradeRowNum != 1
				&& (int) gradeCount != 1) {
			result += GRADE + (int) gradeRowNum + "/" + (int) gradeCount + "；"
					+ "\n";
		}
		if ((classesRowNum / classesCount) > 0.8 && (int) classesRowNum != 1
				&& (int) classesCount != 1) {
			result += CLASSES + (int) classesRowNum + "/" + (int) classesCount
					+ "。" + "\n";
		}
		return result;
	}

	/**
	 * Description:写出完整文档的方法
	 * 
	 * @param content
	 * @param outputPath
	 * @param fileName
	 *            --------------------------------------------------------
	 *            2015-3-11 mhis_hcpms EX-TIANZINONG001 创建
	 */
	public void exportWord(String content, String outputPath, String fileName) {
		try {
			writeRefFile(content, outputPath, fileName);
		} catch (Exception e) {
			LOG.error(e, e);
		}
	}

	/**
	 * Description: 根据图片路径获得图片的字符串，并将字符串的字节数组转换成16进制数
	 * 
	 * @param imgPath
	 * @return ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 */
	@SuppressWarnings("resource")
	private String getImgRtfCode2(String imgPath) {
		FileInputStream fis = null;
		ByteArrayOutputStream bos = null;
		BufferedInputStream bis = null;
		String str = "";
		int num = 1024;
		// 得到图片的字节数组
		byte[] result = null;
		try {
			fis = new FileInputStream(imgPath);
			bis = new BufferedInputStream(fis);
			bos = new ByteArrayOutputStream();
			byte[] buff = new byte[num];
			int len = 0;
			while ((len = bis.read(buff)) != -1) {
				bos.write(buff, 0, len);
			}
			result = bos.toByteArray();

		} catch (FileNotFoundException e) {
			LOG.error(e, e);
		} catch (IOException e) {
			LOG.error(e, e);
		} finally {
			try {
				if (null != bos) {
					bos.close();
				}
				if (null != fis) {
					fis.close();
				}
				if (null != bis) {
					bis.close();
				}
			} catch (IOException e) {
				LOG.error(e, e);
			}
		}
		// 字节数组转成十六进制
		if (null != result) {
			str = "{\\*\\shppict{\\pict\\jpegblip\\picw16\\pich16 "
					+ byte2HexStr(result) + "}}";
		}
		return str;
	}

	/**
	 * Description:字节数组转成十六进制
	 * 
	 * @param b
	 * @return ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 */
	private String byte2HexStr(byte[] b) {
		StringBuilder hs = new StringBuilder();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs.append("0").append(stmp);
			} else {
				hs.append(stmp);
			}
		}
		return hs.toString().toUpperCase();
	}

	/**
	 * Description: 导出文档的方法
	 * 
	 * @param content
	 * @param outputPath
	 * @param fileName
	 * @throws FwaBusinessException
	 *             2015-3-11 mhis_hcpms EX-TIANZINONG001 创建
	 */
	private void writeRefFile(String content, String outputPath, String fileName)
			throws FwaBusinessException {

		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(outputPath + fileName);
			fos.write(content.getBytes("GB2312"));
		} catch (IOException e) {
			LOG.error(e, e);
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				LOG.error(e, e);
			}
		}
	}

	/**
	 * Description: 获得模板字符串的方法
	 * 
	 * @param filePath
	 * @return String
	 * 
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 */
	public String getContent(String filePath) {
		StringBuilder source = new StringBuilder();
		InputStream ins = null;
		int len = 1024;
		try {
			ins = new FileInputStream(filePath);
			byte[] b = new byte[len];
			int readLength = 0;
			while (true) {
				readLength = ins.read(b, 0, len);
				if (readLength == -1) {
					break;
				}
				source.append(new String(b, 0, readLength, "utf-8"));
			}
		} catch (Exception e) {
			LOG.error(e, e);
		} finally {
			try {
				if (ins != null) {
					ins.close();
				}
			} catch (IOException e) {
				LOG.error(e, e);
			}
		}
		return source.toString();
	}

	/**
	 * Description: 替换模板字符串的占位符的方法
	 * 
	 * @param content
	 * @param contextMap
	 * @return String
	 * 
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 */
	private String replaceContentForCode(String content,
			Map<String, Object> contextMap) {
		String str = content;
		try {
			for (Map.Entry<String, Object> entry : contextMap.entrySet()) {
				str = str.replaceAll(entry.getKey(), entry.getValue() + "");
			}
		} catch (Exception e) {
			LOG.error(e, e);
		}
		return str;
	}

	/**
	 * Description: 读取rtf文件中文本字符串的方法，去掉格式的占位符
	 * 
	 * @param content
	 * @return String
	 * 
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 */
	private String getStrRtfCode(String content) {
		char[] digital = "0123456789ABCDEF".toCharArray();
		StringBuilder sb = new StringBuilder("");
		byte[] bs = null;
		int num = 4;
		try {
			bs = content.getBytes("GB2312");
			int bit;
			for (int i = 0; i < bs.length; i++) {
				bit = (bs[i] & 0x0f0) >> num;
				sb.append("\\loch\\af0\\hich\\af0\\dbch\\f13 ");
				sb.append("\\'");
				sb.append(digital[bit]);
				bit = bs[i] & 0x0f;
				sb.append(digital[bit]);
			}
		} catch (Exception e) {
			LOG.error(e, e);
		}

		return sb.toString();
	}

	/**
	 * Description: 获取 rtf表格字符串形式的方法
	 * 
	 * @param tabPath
	 * @return String
	 * 
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-TIANZINONG001 创建
	 */
	private String getTableCode(String tabPath) {
		InputStream input = null;
		int bytesRead = 0;
		StringBuilder sourceText = new StringBuilder();
		String result = "";
		int length = 1024;
		int five = 5;
		byte[] b = new byte[length];
		try {
			input = new FileInputStream(tabPath);
			while (true) {
				bytesRead = input.read(b, 0, length);
				if (bytesRead == -1) {
					break;
				}
				sourceText.append(new String(b, 0, bytesRead, "utf-8"));
			}
			int startIdx = sourceText.indexOf("info}") + five;
			int endIdx = sourceText.length() - 1;
			result = sourceText.substring(startIdx, endIdx);
			result = new String(result.getBytes("utf-8"), "gb2312");
		} catch (FileNotFoundException e) {
			LOG.info("文件没找到");
			LOG.error(e, e);
		} catch (UnsupportedEncodingException e) {
			LOG.info("字符编码转化异常");
			LOG.error(e, e);
		} catch (IOException e) {
			LOG.info("IO异常");
			LOG.error(e, e);
		} finally {
			try {
				if (null != input) {
					input.close();
				}
			} catch (IOException e) {
				LOG.error(e, e);
			}
		}
		return result;
	}

	/**
	 * Description:画出图片的方法JFreeChar
	 * 
	 * @param dirPath
	 * @param healthcareProviderCode
	 * @param kpiTime
	 * @param indicatorList
	 * @param size
	 * @return
	 * @throws IOException
	 * 
	 *             2015-3-11 mhis_hcpms EX-TIANZINONG001 创建
	 */
	public String findPngFilePath(String dirPath,
			String healthcareProviderCode, String kpiTime,
			List<ArrayList<SecondLevelIndicatorDto>> indicatorList, int[] size)
			throws IOException {

		List<String> legendtitleList = new ArrayList<String>();
		legendtitleList.add("上期分数");
		legendtitleList.add("本期分数");
		legendtitleList.add("同级别机构平均");

		JFreeChart jfchart = ScaleSpriderWebPlotFactory.createChart(null,
				legendtitleList, indicatorList);
		jfchart.setBackgroundPaint(Color.WHITE);

		BufferedOutputStream bos = null;
		File pngFile = null;
		String pngFilePng = null;

		pngFile = new File(dirPath, healthcareProviderCode + "_" + kpiTime
				+ ".png");
		bos = new BufferedOutputStream(new FileOutputStream(pngFile));
		ChartUtilities.writeChartAsPNG(bos, jfchart, size[0], size[1]);
		pngFilePng = pngFile.getAbsolutePath();

		if (bos != null) {
			bos.flush();
			bos.close();
			bos = null;
		}

		return pngFilePng;
	}

	/**
	 * Description: 生成医院得分详情表格文档
	 * 
	 * @param list
	 *            dto对象的集合
	 * @param filePath
	 *            生成文件的路径
	 *            --------------------------------------------------------
	 *            2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	public void createTable(List<ScoreTableDTO> list, String filePath) {

		// 获得文档对象
		Document doc = new Document();
		// table对象
		Table table = null;
		try {
			RtfWriter2.getInstance(doc, new FileOutputStream(filePath));
			doc.open();
			table = new Table(9, searchAllMenuNumber(list));
			table.setWidth(100F);
			int[] ins = { 100, 60, 100, 60, 180, 60, 80, 120, 100 };
			table.setWidths(ins);
			table.setBackgroundColor(Color.BLACK);
			// 添加表头元素
			addHeaderCell(table);
			addBodyCell(table, list);
			doc.add(table);
			doc.close();
		} catch (FileNotFoundException e) {
			LOG.info("文件未找到");
			LOG.error(e, e);
		} catch (BadElementException e) {
			LOG.error(e, e);
		} catch (DocumentException e) {
			LOG.error(e, e);
		}
	}

	/**
	 * Description:查询一级指标下面所拥有的二级指标的id
	 * 
	 * @param list
	 *            dto的集合
	 * @param code
	 *            父指标的ID
	 * @return 返回map 键是二级指标的id 值是二级指标所拥有三级指标的数目
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	public Map<String, Integer> searchThreeMenu(List<ScoreTableDTO> list,
			String code) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		for (int i = 1; i < list.size(); i++) {
			if (list.get(i).getPid().equals(code)) {
				map.put(list.get(i).getIndicatorCode(),
						searchMenu(list, list.get(i).getIndicatorCode()));
			}
		}
		return map;
	}

	/**
	 * Description: 查询二级指标应该合并的单元格数目
	 * 
	 * @param list
	 *            dto的集合
	 * @param index
	 *            循环的下标
	 * @return 二级指标下拥有的三级指标的数目
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	public int searchMenu(List<ScoreTableDTO> list, String index) {
		int number = 0;
		for (int i = 1; i < list.size(); i++) {
			if (list.get(i).getPid().equals(index)) {
				number++;
			}
		}
		return number;
	}

	/**
	 * Description: 查询所有的三级指标数目
	 * 
	 * @param list
	 *            dto的集合
	 * @return 三级指标的数目 ------------------------------------------------------
	 *         2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	public int searchAllMenuNumber(List<ScoreTableDTO> list) {
		int number = 0;
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getIndicatorLevel() == MENU_GRADE_THREE) {
				number++;
			}
		}
		return number;
	}

	/**
	 * 
	 * Description:添加内容元素
	 * 
	 * @param table
	 *            需要生成的表格对象
	 * @param list
	 *            dto的集合 2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 * @throws BadElementException
	 */
	public void addBodyCell(Table table, List<ScoreTableDTO> list)
			throws BadElementException {

		for (int i = 0; i < list.size(); i++) {
			// 一级指标
			if (list.get(i).getIndicatorLevel() == MENU_GRADE_FIRST) {
				// 创建一级指标
				String first = list.get(i).getIndicatorCode();
				createFirstMenu(table, list, i);
				for (int j = 0; j < list.size(); j++) {
					// 创建二级指标
					createMenu(table, list, first, j);
				}
			}
		}
	}

	/**
	 * 
	 * Description: 添加内容元素
	 * 
	 * @param table
	 *            需要生成的表格对象
	 * @param list
	 *            dto的集合
	 * @param first
	 *            一级指标的ID
	 * @param j
	 *            循环的下标 2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 * @throws BadElementException
	 */
	private void createMenu(Table table, List<ScoreTableDTO> list,
			String first, int j) throws BadElementException {
		// 二级指标
		if ((list.get(j).getIndicatorLevel() == MENU_GRADE_SECOND)
				&& (list.get(j).getPid().equals(first))) {
			// 创建二级指标
			String second = list.get(j).getIndicatorCode();
			createSecondMenu(table, list, j);
			for (int k = 0; k < list.size(); k++) {
				// 三级指标
				if ((list.get(k).getIndicatorLevel() == MENU_GRADE_THREE)
						&& (list.get(k).getPid().equals(second))) {
					// 创建三级指标
					createThreeMenu(table, list, k);
				}
			}
		}
	}

	/**
	 * Description:将compareRange int 转成String
	 * 
	 * @param comparerange
	 *            compareRange的值
	 * @return 转换后的String ------------------------------------------------------
	 *         2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	public String showCompareRange(String compareRange, String number) {
		String str = "";
		if (compareRange == null) {
			return "本机构";
		}
		if (null == number) {
			if ("1".equals(compareRange)) {
				str = "全部机构";
			} else if ("2".equals(compareRange)) {
				str = "同级机构";
			} else if ("3".equals(compareRange)) {
				str = "本机构";
			} else if ("4".equals(compareRange)) {
				str = "二级及以上机构";
			}
		} else {

			if ("1".equals(compareRange)) {
				str = "全部机构，" + number + "个月";
			} else if ("2".equals(compareRange)) {
				str = "同级机构，" + number + "个月";
			} else if ("3".equals(compareRange)) {
				str = "本机构，" + number + "个月";
			} else if ("4".equals(compareRange)) {
				str = "二级及以上机构，" + number + "个月";
			}
		}
		return str;
	}

	/**
	 * Description: 添加表头元素
	 * 
	 * @param table
	 *            需要生成的表格对象 2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 * @throws BadElementException
	 */
	public void addHeaderCell(Table table) throws BadElementException {
		String[] title = { "一级指标", "实际得分/满分分值", "二级指标", "实际得分/满分分值", "三级指标",
				"实际得分/满分分值", "指标实际值", "在对比范围内满分区间 ", "对比范围" };
		Cell cell = null;
		for (int i = 0; i < title.length; i++) {
			Font fontBody = new Font();
			fontBody.setSize(11);
			Paragraph body = new Paragraph(GeneralMethods.getInstance()
					.addBlankForString(title[i]), fontBody);
			cell = new Cell(body);
			cell.setHeader(true);
			cell.setBorderWidth(1);
			cell.setBackgroundColor(Color.BLACK);
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
		}
	}

	/**
	 * Description: 一级指标
	 * 
	 * @param table
	 *            需要生成的表格对象
	 * @param list
	 *            dto的集合
	 * @param index
	 *            循环时进入该方法的下标 2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 * @throws BadElementException
	 */
	private void createFirstMenu(Table table, List<ScoreTableDTO> list,
			Integer index) throws BadElementException {
		Map<String, Integer> map = searchThreeMenu(list, list.get(index)
				.getIndicatorCode());

		Set<String> keySet = map.keySet();

		int allSpan = 0;

		for (String i : keySet) {
			allSpan += map.get(i);
		}

		String[] title = {
				list.get(index).getIndicatorDesc(),
				AssessmentUtils.decimalToString(list.get(index)
						.getStructureScore())
						+ "/"
						+ AssessmentUtils.decimalToString(list.get(index)
								.getFullScore()) };
		for (int i = 0; i < title.length; i++) {
			Font fontBody = new Font();
			fontBody.setSize(9);
			Paragraph body = new Paragraph(GeneralMethods.getInstance()
					.addBlankForString(title[i]), fontBody);
			Cell cell = new Cell(body);
			cell.setBorderWidth(1);
			cell.setRowspan(allSpan);
			cell.setBackgroundColor(Color.BLACK);
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
		}

	}

	/**
	 * 
	 * Description: 二级指标
	 * 
	 * @param table
	 *            需要生成的表格对象
	 * @param list
	 *            dto的集合
	 * @param index
	 *            循环时进入该方法的下标
	 * 
	 *            2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 * @throws BadElementException
	 */
	private void createSecondMenu(Table table, List<ScoreTableDTO> list,
			Integer index) throws BadElementException {
		int number = searchMenu(list, list.get(index).getIndicatorCode());
		String[] title = {
				list.get(index).getIndicatorDesc(),
				AssessmentUtils.decimalToString(list.get(index)
						.getStructureScore())
						+ "/"
						+ AssessmentUtils.decimalToString(list.get(index)
								.getFullScore()) };
		BaseFont bs = null;
		try {
			bs = BaseFont.createFont();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Font fontBody = new Font(bs, 9, Font.NORMAL);
		for (int i = 0; i < title.length; i++) {
			Paragraph body = new Paragraph(GeneralMethods.getInstance()
					.addBlankForString(title[i]), fontBody);
			Cell cell = new Cell(body);
			cell.setBorderWidth(1);
			cell.setRowspan(number);
			cell.setBackgroundColor(Color.BLACK);
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
		}
	}

	/**
	 * 
	 * Description: 三级指标
	 * 
	 * @param table
	 *            需要生成的表格对象
	 * @param list
	 *            dto的集合
	 * @param index
	 *            循环时进入该方法的下标
	 * 
	 *            Modification History: Date Version Author Description
	 *            2015-3-11 mhis_hcpms EX-ZENGYUANCHAO001 创建
	 * @throws BadElementException
	 */
	private void createThreeMenu(Table table, List<ScoreTableDTO> list,
			Integer index) throws BadElementException {

		String[] title = {
				list.get(index).getIndicatorDesc()
						+ getStringUnit(list.get(index).getUnit()),
				list.get(index).getStructureScore() == null ? ""
						: AssessmentUtils.decimalToString(list.get(index)
								.getStructureScore())
								+ "/"
								+ AssessmentUtils.decimalToString(list.get(
										index).getFullScore()),
				list.get(index).getFullMark().toString() == null ? ""
						: AssessmentUtils.decimalToString(list.get(index)
								.getFullMark()),
				getForSourceType(list, index, list.get(index).getSourceType()),
				showCompareRange(list.get(index).getCompareRange(),
						list.get(index).getTimeRange()) };
		Font fontBody = FontFactory.getFont("Microsoft YaHei",
				BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED, 9);
		for (int i = 0; i < title.length; i++) {
			Paragraph body = new Paragraph(GeneralMethods.getInstance()
					.addBlankForString(title[i]), fontBody);
			Cell cell = new Cell(body);
			cell.setBorderWidth(1);
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setBackgroundColor(Color.BLACK);
			cell.setVerticalAlignment(Element.ALIGN_CENTER);
			table.addCell(cell);
		}
	}

	/**
	 * 
	 * Description:获得指标的单位
	 * 
	 * @param bi
	 * @return
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-26
	 *         mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	private String getStringUnit(String unit) {
		if (null != unit) {
			return "(" + unit + ")";
		}
		return "";
	}

	private static String getStringForBig(BigDecimal bi) {
		if (null == bi) {
			return "";
		} else {
			return bi + "";
		}
	}

	/**
	 * 
	 * Description: 查询指标来源
	 * 
	 * @param list
	 *            查询的结果
	 * @param index
	 *            遍历的下标
	 * @param sourceType
	 *            指标的来源
	 * @return
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-26
	 *         mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	private String getForSourceType(List<ScoreTableDTO> list, Integer index,
			String sourceType) {
		String valueLimit = "";
		if (StringUtils.isNotBlank(getStringForBig(list.get(index)
				.getLowerLimit()))
				&& StringUtils.isNotBlank(getStringForBig(list.get(index)
						.getUpperLimit()))) {
			valueLimit = " 【 "
					+ AssessmentUtils.decimalToString(list.get(index)
							.getLowerLimit())
					+ ","
					+ AssessmentUtils.decimalToString(list.get(index)
							.getUpperLimit()) + " 】 ";
		}
		if ((AssessmentConstants.STANDARD_TYPE1).equals(sourceType)
				|| (AssessmentConstants.STANDARD_TYPE2).equals(sourceType)) {
			return valueLimit;
		}
		if ((AssessmentConstants.STANDARD_TYPE3).equals(sourceType)) {
			return "是";
		}
		return "";
	}

	private String getLastDayOfMonth(String kpiTime) {
		int year = Integer.parseInt(kpiTime.split("-")[0]);
		int month = Integer.parseInt(kpiTime.split("-")[1]);
		Calendar cal = Calendar.getInstance();
		// 设置年份
		cal.set(Calendar.YEAR, year);
		// 设置月份
		cal.set(Calendar.MONTH, month - 1);
		// 获取某月最大天数
		int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		// 设置日历中月份的最大天数
		cal.set(Calendar.DAY_OF_MONTH, lastDay);
		// 格式化日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String lastDayOfMonth = sdf.format(cal.getTime());

		return lastDayOfMonth;

	}

}
